const app = getApp()
var util = require('../../utils/util.js');
var WCHBLEWxJsLib = require('../../utils/WCHBLEWxJsLib.js');
var exception = require("../../utils/exception.js");


// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}



Page({
  data: {
    devices: [],
    connected: false,
    chs: [],
    currentBtn:1,
    windowHeight: 0,
    scrollViewHeight: 0,
    
    openBlueFlag:false,
    loading:true,
    modalName:'',
    showStr:null,
    scrollTop:'',
    icon1:'/pages/assets/img/icon1.png',
    icon2:'/pages/assets/img/icon2.png',
    icon3:'/pages/assets/img/icon3.png',
    icon4:'/pages/assets/img/icon4.png',

  },

onShow: function () {
  console.log()

  var that = this

  wx.setNavigationBarTitle({
       title: '蓝牙列表'
   })

   wx.showLoading({
     title: '正在加载...',
     duration:500
   })
    
  wx.getSystemInfo({
    success: function(res) {
      that.setData({
        windowHeight: res.windowHeight
      });
    }
  });
 
  let query = wx.createSelectorQuery().in(this);
  query.select('#header').boundingClientRect();
  query.exec((res) => {
    let headerHeight = res[0].height;
    let scrollViewHeight = this.data.windowHeight - headerHeight
    this.setData({
      scrollViewHeight: scrollViewHeight
    });
    // wx.hideLoading({ })
    console.log(this.data.scrollViewHeight,'height')
    this.openBluetoothAdapter()
    
  });

  if(app.globalData.sendTimer){
    this.setData({
      sendFlag:true
    })
   clearInterval(app.globalData.sendTimer)
  }

  if(app.globalData.timer){
     clearInterval(app.globalData.timer)
  }

  var version = WCHBLEWxJsLib.getSDKVersion();
  wx.showToast({
    title: version,
    icon:"none",
    duration:3000
  })
},

onHide(){
  this.setData({
    devices: [],
    connected: false,
    chs: [],
  })
  if(this.data.currentBtn==1){
    WCHBLEWxJsLib.disconnectBLEDevice(null,this.data.connected,this.data.deviceId,this).then(res=>{
      console.log(res)
    }).catch(err=>{
      console.log(err)
    })
  }

},

onLoad: function(options) {
    if(options.url){
 
      let url = decodeURIComponent(options.url);
      wx.navigateTo({
        url
      })
 
    }else{
      var that = this

    //获取当前设备平台以及微信版本
    if (app.getPlatform() == 'android' && util.versionCompare('6.5.7', app.getWxVersion())) {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，请更新至最新版本',
        showCancel: false,
        success: function(res) {
          if (res.confirm) {
            that.backPage();
          }
        }
      })

    } else if (app.getPlatform() == 'android' && util.versionCompare('4.3.0', app.getSystem())) {
      wx.showModal({
        title: '提示',
        content: '当前系统版本过低，请更新至Android4.3以上版本',
        showCancel: false,
        success: function(res) {
          if (res.confirm) {
            that.backPage();
          }
        }
      })
    } else if (app.getPlatform() == 'ios' && util.versionCompare('6.5.6', app.getWxVersion())) {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，请更新至最新版本',
        showCancel: false,
        success: function(res) {
          if (res.confirm) {
            that.backPage();
          }
        }
      })
    }

    }


},


  // 1.初始化蓝牙
  openBluetoothAdapter() {
    if(this.data.openBlueFlag){
      this.closeBluetoothAdapter(this);
    }
    this.setData({
        currentBtn:1,
        openBlueFlag:true,
        devices: [],
        connected: false,
        chs: [],
    })
    WCHBLEWxJsLib.startEnumBluetoothDevices(this).then(res=>{
      console.log(res)
    }).catch(err=>{
      console.log(err)
    })
    //监听蓝牙适配器状态变化事件
    WCHBLEWxJsLib.watchBluetoothAdapterStateChange(this).then(result=>{
      console.log(result)
    }).catch(error=>{
      wx.showToast({
        title: error.message,
        icon: 'loading',
      })
    })
  },
  


  // 2. 结束蓝牙扫描
  stopBluetoothDevicesDiscovery() {
    wx.showLoading({
      title: '正在停止',
      icon:'none',
      duration:1000
    })
    WCHBLEWxJsLib.stopEnumBluetoothDevices().then((res)=>{
      this.setData({
        currentBtn:2
      })
      console.log(res)
    }).catch((error)=>{
      console.log(error)
    });
  },

  // 3. 创建BLE连接
  createBLEConnection(e) {
    wx.showToast({
      title: '正在创建连接',
      icon: 'loading',
    })
    const ds = e.currentTarget.dataset;
    const deviceId = ds.deviceId;
    const datasetName = ds.name;
    WCHBLEWxJsLib.connectBLEDevice(deviceId,datasetName,this).then(res=>{
      console.log(res)
      wx.showToast({
        title: '蓝牙连接成功',
        icon: 'none',
        duration: 1000
      })
    }).catch(error=>{
      wx.showToast({
        title: '蓝牙连接失败',
        icon: 'none',
        duration: 1000
      })
      console.log(error)
    })
  },


  //4. 关闭蓝牙模块
  closeBluetoothAdapter() {
    wx.closeBluetoothAdapter()
    this._discoveryStarted = false
    this.setData({
      openBlueFlag:false
    })
    console.log('关闭进程')
  },

 
})
